package com.cal.utms.dao.maintenance;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.cal.utms.entity.Custodian;
import com.cal.utms.util.HibernateUtil;

public class CustodianDao {

	public Object add(Custodian custodian) {
		Object obj;
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			obj = session.save(custodian);
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
			obj = new Object();
			System.out.println("Exception save Custodian " + ex.getMessage());
			ex.printStackTrace();
		} finally {
			session.close();
		}
		return obj;
	}

	public Custodian getById(Integer id) {
		Session session = HibernateUtil.getSession().openSession();
		Custodian custodian = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			custodian = (Custodian) session.get(Custodian.class, id);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			System.out.println("Exception getByID Custodian " + e.getMessage());
		} finally {
			session.close();
		}
		return custodian;
	}

	@SuppressWarnings("unchecked")
	public List<Custodian> getList() {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<Custodian> custodianList = null;
		try {
			tx = session.beginTransaction();
			custodianList = session.createQuery("from Custodian").list();
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			System.out.println("Exception getCustodianList " + e.getMessage());
		} finally {
			session.close();
		}
		return custodianList;
	}

	public static void main(String[] args) {
		CustodianDao custD = new CustodianDao();
		
/*		Custodian cus = new Custodian();
		cus.setName("TeThre");
		cus.setDescription("TestDescForThree");
		custD.add(cus);*/
		
		List<Custodian>  cusList = custD.getList();
		for(Custodian custd:cusList){
			System.out.println(custd.getId()+":"+custd.getName()+":"+custd.getDescription());
		}
		
		System.out.println("!!!!");
		System.out.println(custD.getById(2).getName());
		
	}

}
